package com.link.base.base.contacts.service;

import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.cmqres.model.CmqRes;
import com.link.base.base.cmqres.service.CmqResService;
import com.link.base.base.common.model.InterObject;
import com.link.base.base.contacts.dao.mybatis.mapper.ContactsMapper;
import com.link.base.base.contacts.model.Contacts;
import com.link.base.base.duty.dao.mybatis.mapper.DutyPostnMapper;
import com.link.base.base.duty.model.DutyPostn;
import com.link.base.base.duty.service.DutyService;
import com.link.base.base.mvg.dao.mybatis.accnt.mapper.ContactOrgMvgMapper;
import com.link.base.base.mvg.model.Mvg;
import com.link.base.base.position.dao.mybatis.mapper.PositionMapper;
import com.link.base.base.position.model.Position;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.mq.util.MqUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/9 14:20
 */

@Service
public class ContactsServiceImpl extends BasicServiceImpl<Contacts> implements ContactsService {

    @Resource
    private ContactsMapper contactsMapper;
    @Resource
    private CmqResService cmqResService;
    @Resource
    private ContactOrgMvgMapper contactOrgMvgMapper;
    @Resource
    private UserService userService;
    @Resource
    private DutyService dutyService;
    @Resource
    private PositionMapper positionMapper;
    @Resource
    private DutyPostnMapper dutyPostnMapper;

    /**
     * 在删除地址之后，触发cmq发送逻辑，获取对象信息 HuangLJ 2017年12月28日
     */
    private Contacts contacts;

    @Override
    public BasicMapper<Contacts> getBasicMapper() {
        return contactsMapper;
    }

    @Override
    public Contacts preDefaultValue(Contacts entity) throws Exception {
        Long contactsId = entity.getId();
        if (null == contactsId) {
            contactsId = keyGenerateService.keyGenerate();
            entity.setId(contactsId);
        }

        CoreUser user = UserUtil.getUser();
        //将登录人的当前职位设置为联系人的默认职位
        Long postnId = user.getPostnId();
        if (null != postnId) {
            entity.setPostnId(postnId);
            entity.setPostnName(user.getPostnName());
        }

        //将登录人的当前组织设置为联系人的默认组织，包括组织mvg
        Long orgId = user.getOrgId();
        if (null != orgId) {
            entity.setOrgId(orgId);
            entity.setOrgName(user.getOrgName());
            Mvg mvgEntity = new Mvg();
            mvgEntity.setId(keyGenerateService.keyGenerate());
            mvgEntity.setMvgParentId(contactsId);
            mvgEntity.setMvgSubsetId(orgId);
            contactOrgMvgMapper.insert(mvgEntity);
        }
        return entity;
    }

    /**
     * 查找非子客户及本身
     *
     * @param contacts
     * @return
     * @throws Exception
     */
    @Override
    public List<Contacts> queryContactsListRemoveIdAndChildrenPage(Contacts contacts) throws Exception {
        String dataBase = "mysql";
        if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBase)) {
            String str = contactsMapper.getChildStr(contacts);
            contacts.setAttr6(str);
        }
        return contactsMapper.queryContactsListRemoveIdAndChildrenPage(contacts);
    }

    /**
     * 联系人树形结构
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public List<Contacts> contactsTreeList(Contacts entity) throws Exception {

        //获取根节点Id
        Contacts c = contactsMapper.queryRoot(entity);
        List<Contacts> contactsList = null;
        //获取树结构
        String dataBase = "mysql";
        if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBase)) {
            String str = contactsMapper.getChildStr(c);
            contactsList = contactsMapper.queryChildTreeList(str);
        } else {
            contactsList = contactsMapper.queryChildTreeList(c);
        }
        List<Contacts> nodeList = new ArrayList<Contacts>();
        for (Contacts c1 : contactsList) {
            if (c1.getPosition() == null) {
                c1.setPosition("无");
            }
            boolean mark = false;
            for (Contacts c2 : contactsList) {
                if (c1.getParContactId() != null && c1.getParContactId().equals(c2.getId())) {
                    mark = true;
                    if (c2.getChildren() == null) {
                        c2.setChildren(new ArrayList<Contacts>());

                    }
                    c2.getChildren().add(c1);
                    break;
                }
            }
            if (!mark) {
                nodeList.add(c1);
            }
        }

        for (Contacts contacts : nodeList) {
            System.out.println(contacts.toString());
        }

        return nodeList;
    }

    @Override
    public void afterUpdate(Contacts contacts) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Long accntId = contacts.getAcctId();
                if (accntId != null) {
                    String message1 = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";
                    String message2 = "\"}";
                    String message = message1 + accntId + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    @Override
    public void afterInsert(Contacts contacts) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Long accntId = contacts.getAcctId();
                if (accntId != null) {
                    String message1 = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";
                    String message2 = "\"}";
                    String message = message1 + accntId + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    @Override
    public void beforDelete(Contacts contacts) throws Exception {
        //在删除地址之后，触发cmq发送逻辑，获取对象信息 HuangLJ 2017年12月28日
        this.contacts = this.queryById(contacts);
    }

    /**
     * 发送消息到cmq
     *
     * @param contacts
     * @throws Exception
     */

    @Override
    public void afterDelete(Contacts contacts) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Long accntId = this.contacts.getAcctId();
                if (accntId != null) {
                    String message1 = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";
                    String message2 = "\"}";
                    String message = message1 + accntId + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }


    /**
     * 客户联系人创建用户账号
     *
     * @param entity
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public User createdUserAccount(Contacts entity) throws Exception {
        Contacts object = contactsMapper.queryById(entity);
        DutyPostn dutyPostn = new DutyPostn();
        //查询职位角色管理信息
        dutyPostn.setId(object.getDutyPostnId());
        dutyPostn = dutyPostnMapper.queryById(dutyPostn);
        if (null == object.getSystermRoleId()) {
            throw new ServiceException("CONTRACTS-001");
        }
        if (StringUtils.isBlank(object.getSystermUserName())) {
            throw new ServiceException("CONTRACTS-002");
        }
        if (dutyPostn == null) {
            throw new ServiceException("CONTRACTS-003");
        }
        if (null == dutyPostn.getRoleId()) {
            throw new ServiceException("CONTRACTS-004");
        }
        if (null != object.getUserId()) {
            User user = new User();
            user.setId(object.getUserId());
            User userObj = userService.getUserByUserId(user);
            userObj.setUsername(object.getSystermUserName());
            userObj.setContactPhone(object.getMobilePhone());
            userObj.setFirstName(object.getContactsName());
            userObj.setEmail(object.getEmail());
            userObj.setDutyId(dutyPostn.getRoleId());
            userObj.setStatus("NORMAL");
            userService.update(userObj);
            //更新职位信息
            Position updatePosition = new Position();
            updatePosition.setId(userObj.getPostnId());
            updatePosition = positionMapper.queryById(updatePosition);

            updatePosition.setPositionType(dutyPostn.getVal());
            positionMapper.update(updatePosition);

            /*联系人状态变有效*/
            String isEffective = "N";
            if (isEffective.equals(object.getIsEffective())) {
                object.setIsEffective("Y");
                update(object);
            }

            /*给用户添加职责*/
            InterObject interObject = new InterObject();
            interObject.setRearObjId(userObj.getId());
            dutyService.delDutyByUserId(interObject);

            User dutyUser = new User();
            dutyUser.setDutyId(dutyPostn.getRoleId());
            dutyUser.setId(userObj.getId());
            dutyService.addUserOfDutyInsert(dutyUser);

            return userObj;
        } else {
            User user = new User();
            user = userService.getUserByUsername(object.getSystermUserName().toUpperCase());
            if (user != null) {
                throw new ServiceException("CONTRACTS-005");
            }
            User newUser = new User();
            CoreUser loginUser = UserUtil.getUser();
            newUser.setUsername(object.getSystermUserName());
            newUser.setContactPhone(object.getMobilePhone());
            newUser.setFirstName(object.getContactsName());
            newUser.setAcctId(object.getAcctId());
            newUser.setEmail(object.getEmail());
            newUser.setDutyId(dutyPostn.getRoleId());
            newUser.setGender(object.getGender());
            newUser.setEmpType("DealerEmployee");
            newUser.setStatus("NORMAL");
            newUser.setOrgId(loginUser.getOrgId());

            /*创建用户账号*/
            userService.insert(newUser);

            /*查询创建的账号*/
            User userObj = userService.getUserByUsername(object.getSystermUserName().toUpperCase());
            //新建职位
            Position position = new Position();

            Long postId = keyGenerateService.keyGenerate();
            position.setId(postId);
            position.setText("经销商员工-" + object.getContactsName());
            position.setDeptId(loginUser.getOrgId());
            position.setUserId(userObj.getId());
            position.setPositionType(dutyPostn.getVal());
            position.setParentPositionId(loginUser.getCorpid());
            position.setIsEffective("Y");
            positionMapper.insert(position);

            userObj.setPostnId(postId);
            userService.update(userObj);

            /*账号初始化密码*/
            userService.genPsw(userObj);
            User userObj1 = userService.getUserByUsername(object.getSystermUserName().toUpperCase());

            /*联系人写入用户id*/
            object.setUserId(userObj.getId());
            update(object);

            /*给用户添加职责*/
            User dutyUser = new User();
            dutyUser.setDutyId(dutyPostn.getRoleId());
            dutyUser.setId(userObj.getId());
            dutyService.addUserOfDutyInsert(dutyUser);
            return userObj;
        }
    }


    /**
     * 客户联系人用户账号禁用
     *
     * @param entity
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void disableUserAccount(Contacts entity) throws Exception {
        User user = new User();
        user.setId(entity.getUserId());
        user.setStatus("QUIT");
        userService.userStatusUpdate(user);
        entity.setIsEffective("N");
        statusUpdate(entity);
    }

    /**
     * 更新联系人状态
     *
     * @param entity
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void statusUpdate(Contacts entity) throws Exception {
        contactsMapper.statusUpdate(entity);
    }

}
